package org.wwy.demo;

import com.aspose.words.Document;
import com.aspose.words.License;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.extractor.POIXMLTextExtractor;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.xmlbeans.XmlException;

import java.io.*;
import java.util.List;

public class MainStart {
    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = MainStart.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param wordPath 需要被转换的word全路径带文件名
     * @param pdfPath 转换之后pdf的全路径带文件名
     */
    public static void doc2pdf(String wordPath, String pdfPath) throws Exception {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        long old = System.currentTimeMillis();
        File file = new File(pdfPath); //新建一个pdf文档
        FileOutputStream os = new FileOutputStream(file);
        Document doc = new Document(wordPath); //Address是将要被转化的word文档
        doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
        long now = System.currentTimeMillis();
        os.close();
        System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); //转化用时

    }





    public static void main(String[] args) throws Exception {
        String filePaths = null;
        String pdfPath = null;
        if(args == null || args.length==0){
            //word 和excel 转为pdf
            filePaths="D:/ChromeCoreDownloads/易方达中债3-5年期国债指数证券投资基金_2020年02月投资月报.docx";
            String fileName="abc";
            pdfPath="e:/"+fileName+".pdf";
            //doc2pdf(filePaths, pdfPath);//filePaths需要转换的文件位置 pdfPath为存储位置
//         String excel2pdf="D:/logs/excelToPdf.xlsx";
        }else {
            filePaths = args[0];
            pdfPath = args[1];
        }

        doc2pdf(filePaths,pdfPath);
    }

    public static POIXMLTextExtractor readWord(String path) throws IOException, OpenXML4JException, XmlException {
        OPCPackage opcPackage = POIXMLDocument.openPackage(path);
        POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
        return extractor;

    }



}
